from __future__ import print_function
from run_game import GameRunner
from gameconsts import TIE
from itertools import permutations
import re

if __name__ == '__main__':
    with open('tournament_log.txt', 'w') as the_file:
        the_file.write('')
        the_file.close()

    with open('moveOrdering_log.txt', 'w') as the_file:
        the_file.write('')
        the_file.close()

    setupTime = 2
    times = [2.5, 10, 40]
    k = 5
    numOfMovesPerGame = 100

    L_players = ['simple_player', 'improved_heuristic_player', 'selective_deepening_player','combined_player', 'combined_player_with_ordering']
    D_scores = {player:  {time: 0 for time in times} for player in L_players}

    tournament = []
    mode = 'single'

    if mode == 'single':
        game = GameRunner(setupTime, 40, k, numOfMovesPerGame , '', 'combined_player_with_ordering', 'improved_heuristic_player').run()
        exit()

    if mode == '1 vs 100':
        tournament = zip(['combined_player_with_ordering']*(len(L_players)-1), L_players)
        tournament.extend(zip((L_players), ['combined_player_with_ordering']*len(L_players)))
        temp = [(y,x) for x,y in tournament]
        tournament.extend(temp)

    elif mode == 'all':
        tournament = permutations(L_players, 2)

    for white, black in tournament:
        for time in times:
            print('{} vs {} with {} secs per k moves'.format(white, black, time))
            with open('moveOrdering_log.txt', 'a') as the_file:
                the_file.write('{} vs {} with {} secs per k moves'.format(white, black, time))
                the_file.close()

            game = GameRunner(setupTime, time, k, numOfMovesPerGame , '', white, black)
            winner_string = game.run()
            if winner_string == TIE:
                D_scores[white][time] += 0.5
                D_scores[black][time] += 0.5
            else:
                winner_match = re.search(r'\w+_player\w*',str(winner_string))
                if not winner_match:
                    print("ERROR: no match found, winner is : {}".format(winner_string))
                    exit()
                winner = winner_match.group()
                D_scores[winner][time] += 1
    the_file = open('tournament_log.txt', 'a')
    for player, D_score in D_scores.items():
        for time, score in D_scores[player].items():
            print('player: {:30} score: {:1} time: {}'.format(player, score, time))
            the_file.write('player: {:30} score: {:1} time: {}\n'.format(player, score, time))
    the_file.close()
